package cn.com.dhc.danlu.receiver.network;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import java.util.ArrayList;

import cn.com.dhc.danlu.util.ToastUtil;

/**
 * @author: 李一方
 * @time: 2016-08-31 10:46
 * @mail: liyifang@danlu.com
 * @desc: 网络状况监听接收器
 */
public class NetworkReceiver extends BroadcastReceiver {
    //网络状态监听集合，使用前需要添加到该集合中
    public static ArrayList<NetworkStateCallback> mListener = new ArrayList<> ();
    private boolean update = false;

    @Override
    public void onReceive (Context context, Intent intent) {
        ConnectivityManager connManager = (ConnectivityManager) context.getSystemService (Context.CONNECTIVITY_SERVICE);
        NetworkInfo gprs = connManager.getNetworkInfo (ConnectivityManager.TYPE_MOBILE);
        NetworkInfo wifi = connManager.getNetworkInfo (ConnectivityManager.TYPE_WIFI);

        if (mListener.size () > 0) {
            for (NetworkStateCallback listener : mListener) {
                if (!update && (wifi.isConnected () || gprs.isConnected ())) {
                    if (wifi.isConnected ()) {
                        ToastUtil.getInstance ().showWifi ();
                        listener.onConnected (ConnectedState.TYPE_WIFI);
                    } else if (gprs.isConnected ()) {
                        ToastUtil.getInstance ().showMobile ();
                        listener.onConnected (ConnectedState.TYPE_MOBILE);
                    }
                    update = true;
                } else if (!wifi.isConnected () && !gprs.isConnected ()) {
                    listener.onDisconnected ();
                    update = false;
                }
            }
        }
    }
}